import React, { useImperativeHandle, useMemo, useState } from 'react';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Badge, Button, Col, Empty, Image, Row, Space, Spin, message } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import cls from 'classnames';
import { useContext, useEffect } from 'react';
import { ISupplierActionEnum, SupplierLocaldataContext } from '../common';
import { getColorTextLoadMap, imageFallbackStr, onMouseOutBtn, searchChangeColor } from '@/utils';
import MyIcon from '@/components/MyIcon';
import { EditOutlined } from '@ant-design/icons';
import { qualifyDataGridServices } from '../services';
import { getBaseUrl } from '@/services/urlconst';

// const qualifications = [
//   //模拟数据-王志龙
//   {
//     expireBegin: '2012-03-12 15:06:06',
//     expireFinish: '2023-02-21 06:05:48',
//     attachContent:
//       '特许经营许可证是一种合同性质的证书，旨在确保特许经营者在特许经营范围内合法经营，并维护特许经营品牌的形象和质量标准。特许经营许可证的颁发和管理通常由特许经营权授予方负责，以确保特许经营者的合法性和品牌形象的统一性。',
//     isExpire: 0,
//     attachTypeName: '特许经营许可证||#417505',
//     attachType: '100131051003',
//     attachURL:
//       'https://ts1.cn.mm.bing.net/th/id/R-C.a849eba8f21fddd95c3795ba28634b8f?rik=6y2ynkg3V6H8%2bA&riu=http%3a%2f%2fimg5.yun300.cn%2frepository%2fimage%2f89ac9827-67ed-4e67-88f9-57c1ed8283d1.jpg_%7bi%7dxaf.jpg%3ftenantId%3d207758%26viewType%3d1&ehk=Z8zwJlU%2fjRaBgT1oRq8EcqEhC1DQloXOfDtO8JZaNNo%3d&risl=&pid=ImgRaw&r=0',
//     createTime: '2022-05-18 15:26:59',
//     createDepartmentName: '采购部',
//     createrName: '袁宇',
//     id: '1',
//   },
//   {
//     expireBegin: '2012-03-12 15:06:06',
//     expireFinish: '2023-02-21 06:05:48',
//     attachContent:
//       '行业许可证证书的颁发旨在确保从事特定行业的经营者或服务提供者具备必要的资质和能力，以保障公众利益和行业规范。持有该证书的企业或个人应遵守相关法规和规定，确保其经营活动或服务符合法律要求和行业标准，维护行业的稳定和可持续发展。证书的有效性和合规性需要定期进行监督和审查，以确保证书持有者的合规经营和服务质量。',
//     isExpire: 1,
//     attachTypeName: '行业许可证||#f5a623',
//     attachType: '100131051006',
//     attachURL:
//       'https://ts1.cn.mm.bing.net/th/id/R-C.a3fb9039dc2a86c9c0410b3a20733781?rik=UsOAyoo7pCS7Cg&riu=http%3a%2f%2fjieyijz.com%2fUploadImage%2f2020317134015953.jpg&ehk=u%2fVbN7AgITuqTxUg%2bwv2Zhk%2bN%2f9bubHopCmQbOQ0LRo%3d&risl=&pid=ImgRaw&r=0',
//     createTime: '2022-05-13 10:06:15',
//     createDepartmentName: '科研部',
//     createrName: '梁旭杰',
//     id: '2',
//   },
//   {
//     expireBegin: '2012-06-12 15:06:06',
//     expireFinish: '2023-02-21 06:05:48',
//     attachContent:
//       '税务登记证是从事生产、经营的纳税人向生产、经营地或者纳税义务发生地的主管税务机关申报办理税务登记时，所颁发的登记凭证。除按照规定不需要发给税务登记证件的外，纳税人办理开立银行账户、申请减税、免税、退税等事项时，必须持税务登记证件。纳税人应将税务登记证件正本在其生产、经营场所或者办公场所公开悬挂，接受税务机关检查。',
//     isExpire: 0,
//     attachTypeName: '税务登记证||#bd10e0',
//     attachType: '100131051002',
//     attachURL:
//       'https://ts1.cn.mm.bing.net/th/id/R-C.51893c16ea0bb92d986ac3415ca02ece?rik=LqFNJrQWD1RVWg&riu=http%3a%2f%2fwww.jxngjs.com%2fuploads%2fueditor%2fimage%2f20200701%2f1593589933688714.jpg&ehk=A3rWKd5XKmkdq%2fnpGX1HkZe%2fifjzRzuWeojoajnFwUk%3d&risl=&pid=ImgRaw&r=0',
//     createTime: '2022-05-13 10:06:15',
//     createDepartmentName: '科研部',
//     createrName: '孙豪宇',
//     id: '3',
//   },
// ];

export const QualifyTabsPaneView = React.forwardRef(({ openIsQualifiModal }: SupplierManageAPI.IQualifyTabsPaneView, ref) => {
  /** 获取上下文 */
  const { updateFixCls, memoirImageRenderID, qualifyDataList, curRes, locationID, supplierDispath, supplierInfoObj } = useContext(SupplierLocaldataContext);

  /** 保存搜索内容 */
  const [qualifySearchValue, setQualifySearchValue] = useState<string>('');

  /** 保存搜索前原始值 */
  const [searchAfterDataList, setSearchAfterDataList] = useState<Record<string, any>[]>([]);

  /** 是否展示放大图片-眼睛状态 */
  const [isShowEye, setIsShowEye] = useState<boolean>(false);

  /**
   * 接口回调
   * @param res
   */
  const qualifyDataGridCallback = (res: any) => {
    if (res && res?.msgFlag) {
      if (res?.rows?.length > 0) {
        supplierDispath({
          type: ISupplierActionEnum.QUALIFYDATA_LIST,
          payload: res?.rows,
        });
      }
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取资质列表 */
  const { qualifyPaneloading, getQualifyPaneDataGrid, refreshQualifyPane } = qualifyDataGridServices(curRes, locationID, qualifyDataGridCallback);

  /** ref 返回事件 */
  useImperativeHandle(ref, () => ({
    refreshQualifyPane,
    getQualifyPaneDataGrid,
    searchQualify,
    reloadQualify,
  }));

  /**初始化 */
  useEffect(() => {
    if (locationID) {
      getQualifyPaneDataGrid({}); //模拟数据-王志龙
    }
  }, [locationID]);

  /**
   * 点击搜索
   * @param params
   */
  const searchQualify = (params: Record<string, any>) => {
    if (supplierInfoObj && supplierInfoObj?.id) {
      getQualifyPaneDataGrid(params);
    } else {
      if (searchAfterDataList && searchAfterDataList?.length == 0) {
        setSearchAfterDataList(qualifyDataList); //模拟数据-王志龙
      }
      const newSearchList: Record<string, any>[] = qualifyDataList?.filter((item: any) => {
        //模拟数据-王志龙
        return item?.attachContent?.includes(params?.attachContent);
      });
      supplierDispath({
        type: ISupplierActionEnum.QUALIFYDATA_LIST,
        payload: newSearchList,
      });
    }
    setQualifySearchValue(params?.attachContent);
  };

  /**
   * 点击重置
   */
  const reloadQualify = () => {
    if (supplierInfoObj && supplierInfoObj?.id) {
      getQualifyPaneDataGrid({});
    } else {
      supplierDispath({
        type: ISupplierActionEnum.QUALIFYDATA_LIST,
        payload: searchAfterDataList,
      });
    }
    setQualifySearchValue('');
  };

  /** 判断编辑按钮权限 */
  const editQualifyBtn = useMemo(() => {
    let showBtn: boolean = false;
    if (curRes?.['/supplierQualifyController/edit']) {
      if (supplierInfoObj && supplierInfoObj?.id) {
        if (supplierInfoObj?.isBlack == '0' && !supplierInfoObj?.cancelerID) {
          showBtn = true;
        }
      } else {
        showBtn = true;
      }
    }
    return showBtn;
  }, [curRes, supplierInfoObj]);

  return (
    <div className={'commonTabsBodyDom'}>
      <Spin spinning={qualifyPaneloading}>
        {qualifyDataList?.length > 0 ? ( //模拟数据-王志龙
          <ScrollBarLayout
            style={{
              margin: '5px 0px',
              padding: '0px 20px',
            }}
          >
            {qualifyDataList?.map((item: any, index: any) => {
              //模拟数据-王志龙
              const { color, colorText } = getColorTextLoadMap(item?.attachTypeName);
              return (
                <Badge.Ribbon key={index + 'AptitudeTabs'} text={colorText || '--'} color={color} placement="start">
                  <div className={cls(pageStyles['commonDlListSty'], `${updateFixCls}aptitudeCardList`, `${updateFixCls}operateBtnAnimarion`)}>
                    <Row>
                      <Col className={`${updateFixCls}aptitudeCardList-titleColTime`} span={24}>
                        {item?.createTime}
                      </Col>
                    </Row>

                    <dl style={{ paddingTop: 10, alignItems: 'flex-end' }}>
                      <dt>
                        <MyIcon type="icon-zizhizhengshu" />
                        &nbsp;相关资质：
                      </dt>
                      <dd>
                        <MyIcon type={'icon-eye'} onClick={() => setIsShowEye(true)} />
                        <Image
                          src={`${getBaseUrl()}${item?.attachURL}`}
                          style={{ display: 'none' }}
                          preview={{
                            visible: isShowEye,
                            getContainer: () => document.getElementById(memoirImageRenderID) as any,
                            onVisibleChange: (value) => {
                              setIsShowEye(value);
                            },
                          }}
                          fallback={imageFallbackStr}
                        />
                      </dd>
                      <dt>
                        <MyIcon type="icon-jiezhishijian" />
                        &nbsp;永久有效：
                      </dt>
                      <dd
                        style={{
                          color: item?.isExpire == '1' ? '#52c41a' : item?.isExpire == '0' ? '#ff0003' : '',
                        }}
                      >
                        {item?.isExpire == '1' ? '是' : item?.isExpire == '0' ? '否' : '--'}
                      </dd>
                    </dl>

                    <dl>
                      <dt>
                        <MyIcon type="icon-time" />
                        &nbsp;开始时间：
                      </dt>
                      <dd>{item?.expireBegin || '--'}</dd>
                      <dt>
                        <MyIcon type="icon-time" />
                        &nbsp;结束时间：
                      </dt>
                      <dd>{item?.isExpire == '0' ? item?.expireFinish || '--' : '--'}</dd>
                    </dl>

                    <dl>
                      <dt>
                        <MyIcon type="icon-bumen" />
                        &nbsp;创建部门：
                      </dt>
                      <dd>{item?.createDepartmentName || '--'}</dd>
                      <dt>
                        <MyIcon type="icon-lianxiren" />
                        &nbsp;创建人：
                      </dt>
                      <dd>{item?.createrName || '--'}</dd>
                    </dl>

                    <dl>
                      <dt>
                        <MyIcon type="icon-baogao" />
                        &nbsp;资质描述：
                      </dt>
                      <dd>{item?.attachContent ? searchChangeColor(item?.attachContent, qualifySearchValue) : '--'}</dd>
                    </dl>

                    {editQualifyBtn && (
                      <Space
                        direction="vertical"
                        size={[0, 8]}
                        className={`${updateFixCls}operateBtnAnimarion-editDelOtherBtn`}
                        style={{
                          top: '12%',
                        }}
                      >
                        <Button
                          onMouseOut={onMouseOutBtn}
                          onClick={() => {
                            openIsQualifiModal({
                              showModal: true,
                              checkRows: item,
                            });
                          }}
                          // icon={<EditOutlined />}
                        >
                          编辑
                        </Button>
                      </Space>
                    )}
                  </div>
                </Badge.Ribbon>
              );
            })}
          </ScrollBarLayout>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
        )}
      </Spin>
    </div>
  );
});
